var ns, UIAlbumBrowser, bmLocation,trans;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            ID: 0,
            RegionName: '',
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: ''
        },
        PlanType: 4,
        imglist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,
        standardlist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        IsAllowWatermark:false,
    },
    methods: {
        get_data: function() {
            var that = this;
            var options = {};
            options.action = "getequipmenttaskdevicedata";
            options.ID = that.form.ID;
            options.PlanType = that.PlanType;
            // console.log(JSON.stringify(options));
            ns.post(options, function(succeed, data, err) {
                // console.log(JSON.stringify(data));
                if (succeed) {
                    that.form = data.formdata;
                    that.standardlist = data.standardlist;
                    that.imglist = data.imglist;
                    that.imgindex = data.imglist.length;
                    that.getIsAllowWatermark();//获取是否只调用相机权限
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_save: function() {
            var that = this;
            if (that.form.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function() {
            api.sendEvent({
                name: 'devicetaskcomplete',
            });
        },
        do_save_process: function(ServiceStatus) {
            var that = this;
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.ID = that.form.ID;
            options.CheckStatus = that.form.CheckStatus;
            options.GPSLocation = that.form.GPSLocation;
            options.ServiceStatus = ServiceStatus;
            options.TaskCompleteContent = that.form.TaskCompleteContent;
            options.PlanType = that.PlanType;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    setTimeout(function() {
                        api.closeWin();
                    }, 1000)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        choose_picture: function() {
            var that = this;
            ns.confirmPer('camera', function() {
                if (that.IsAllowWatermark) {
                    that.upload_choose_picture();
                }
                else {
                    that.choose_picture_start();
                }
            })
        },
        choose_picture_start: function() {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function(ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        UIAlbumBrowser_transPath: function() {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function(ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        remove_img: function(index) {
            var that = this;
            for (var i = 0; i < that.imglist.length; i++) {
                var item = that.imglist[i];
                if (item.index == index) {
                    that.imglist.splice(i, 1);
                    if (item.ID > 0) {
                        that.do_remove_uploadimg(item);
                    }
                }
            }
        },
        do_remove_uploadimg: function(item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function(succeed, data, err) {});
        },
        StartBmap: function() {
            var that = this;
            if (that.form.TaskStatus == 3) {
                return;
            }
            ns.confirmPer('location', function() {
                that.StartLocation();
            })
        },
        StartLocation: function() {
            var that = this;
            if (that.form.TaskStatus == 3) {
                return;
            }
            var num = 0; //次数
            that.form.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function(ret) {
                if (ret.status) {
                    that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber;
                }
            });
        },
        configManager: function() {
            bmLocation.configManager({
                accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
        do_viewimages: function(activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        //获取是否只调用相机权限
        getIsAllowWatermark:function(){
            var that = this;
            if (!that.form.ProjectID) {
                return;
            }
            var options = {
                action: 'getplanparam',
                ProjectID:that.form.ProjectID,
                ConfigKey:'BJPhotoUse'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.IsAllowWatermark = data.type == 2 ? true : false;
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'url',
                allowEdit: false,
                quality: 100,
                saveToPhotoAlbum: false,
                targetWidth: 1750,
                targetHeight: 1800,
            }, function(ret, err) {
                // console.log(JSON.stringify(ret));
                if (ret) {
                    // alert(JSON.stringify(ret));
                    that.waterMark(ret.data);
                         
                } 
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if(!imagePath){
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            var imageName =imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '环境保洁水印', dateTime, that.form.GPSLocation).then((value) => {
                var base64Str=value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath=api.fsDir + '/'+'watermark'+'/'+imageName;
                            that.imglist.push({
                                ID: 0,
                                index: that.imgindex,
                                url:newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                            that.imgindex++;
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                }else{
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    that.imgindex++;
                    return;
                }   
            }) 
        },
    }
});
apiready = function() {
    api.parseTapmode();
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    ns = window.Foresight.Util;
    app.form.ID = api.pageParam.id || 0;
    toast = new auiToast();

    setTimeout(function() {
        app.configManager();
        app.StartBmap();
    }, 1000)
    setTimeout(function() {
        app.get_data();
    }, 500)
    bmLocation.setAgreePrivacy({
        agree: true
    });
}
